const vscode = require('vscode');
const axios = require('axios');
const { v4: uuidv4 } = require('uuid');

/**
 * AI服务类，处理与AI接口的交互
 */
class AIService {
    constructor() {
        this.activeRequests = new Map();
        this.conversationHistory = [];
    }

    /**
     * 发送流式请求到AI服务
     * @param {string} prompt - 提示词
     * @param {Object} options - 选项
     * @param {Function} chunkCallback - 分块响应回调
     * @returns {Promise<string>} - 请求ID
     */
    async streamResponse(prompt, options = {}, chunkCallback) {
        const requestId = uuidv4();
        
        try {
            const apiKey = vscode.workspace.getConfiguration('aiAssistant').get('apiKey');
            const apiEndpoint = vscode.workspace.getConfiguration('aiAssistant').get('apiEndpoint');
            
            if (!apiKey) {
                throw new Error('请先在设置中配置API密钥');
            }
            
            if (!apiEndpoint) {
                throw new Error('请先在设置中配置API端点');
            }
            
            // 记录到活动请求
            this.activeRequests.set(requestId, { 
                controller: new AbortController(), 
                isFinished: false 
            });
            
            // 修复responseType类型问题
            // 发送请求
            const response = await axios({
                method: 'POST',
                url: apiEndpoint,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                data: {
                    messages: JSON.parse(prompt),
                    stream: true,
                    ...options
                },
                responseType: 'stream',
                signal: this.activeRequests.get(requestId).controller.signal
            });
            
            // 处理数据流
            let buffer = '';
            
            response.data.on('data', (chunk) => {
                // 如果请求已被停止，不再处理数据
                if (this.activeRequests.get(requestId)?.isFinished) {
                    return;
                }
                
                const strChunk = chunk.toString();
                buffer += strChunk;
                
                // 分割并处理完整的消息
                let newlineIndex;
                while ((newlineIndex = buffer.indexOf('\n')) !== -1) {
                    const line = buffer.slice(0, newlineIndex).trim();
                    buffer = buffer.slice(newlineIndex + 1);
                    
                    if (line && !line.includes('[DONE]') && chunkCallback) {
                        chunkCallback(line);
                    }
                }
            });
            
            return new Promise((resolve, reject) => {
                response.data.on('end', () => {
                    // 处理缓冲区中剩余的内容
                    if (buffer.trim() && !buffer.includes('[DONE]') && chunkCallback) {
                        chunkCallback(buffer.trim());
                    }
                    
                    // 标记请求完成
                    if (this.activeRequests.has(requestId)) {
                        this.activeRequests.get(requestId).isFinished = true;
                    }
                    
                    resolve(requestId);
                });
                
                response.data.on('error', (error) => {
                    if (this.activeRequests.has(requestId)) {
                        this.activeRequests.get(requestId).isFinished = true;
                    }
                    
                    reject(error);
                });
            });
        } catch (error) {
            console.error('流式请求错误:', error);
            
            // 标记请求完成
            if (this.activeRequests.has(requestId)) {
                this.activeRequests.get(requestId).isFinished = true;
            }
            
            throw error;
        }
    }

    /**
     * 停止响应
     * @param {string} requestId - 请求ID
     * @returns {boolean} - 是否成功停止
     */
    stopResponse(requestId) {
        if (this.activeRequests.has(requestId) && !this.activeRequests.get(requestId).isFinished) {
            this.activeRequests.get(requestId).controller.abort();
            this.activeRequests.get(requestId).isFinished = true;
            return true;
        }
        return false;
    }

    /**
     * 清除对话历史记录
     * @returns {boolean} - 是否成功清除
     */
    clearConversationHistory() {
        try {
            // 清空对话上下文
            this.conversationHistory = [];
            return true;
        } catch (error) {
            console.error('清除对话历史失败:', error);
            return false;
        }
    }
}

module.exports = AIService; 